package com.training.bt.controller;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.training.bt.entity.Tag;
import com.training.bt.entity.User;
import com.training.bt.mapper.TagMapper;
import com.training.bt.security.util.SecurityUtils;
import com.training.bt.service.UserTagService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("api/tag")
@RequiredArgsConstructor
@Slf4j
public class TagController {
    private final UserTagService userTagService;
    private final TagMapper tagMapper;

    // 1. 修复方法名和路径
    @PostMapping("/user-tags")
    public ResponseEntity<Map<String, Object>> saveUserTags(
            @RequestBody List<Long> tagIds) {
        User user = SecurityUtils.getCurrentUser();
        userTagService.saveUserTag(user.getId(), tagIds);
        return ResponseEntity.ok(Collections.singletonMap("message", "用户标签保存成功"));
    }

    // 2. 获取所有标签（可加分页）
    @GetMapping("/tags")
    public ResponseEntity<List<Tag>> getAllTags(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        Page<Tag> tagPage = new Page<>(page, size);
        return ResponseEntity.ok(tagMapper.selectPage(tagPage, null).getRecords());
    }

    // 3. 修复路径和方法名，添加权限控制
    @PostMapping("/tags")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> createTag(
            @RequestParam String name) {
        // 4. 修复存在性检查逻辑
        if(tagMapper.existsByName(name)>=1) {
            return ResponseEntity.badRequest()
                    .body(Collections.singletonMap("error", "标签名称已存在"));
        }
        
        Tag newTag = new Tag();
        newTag.setName(name);
        tagMapper.insert(newTag);
        
        // 5. 返回新创建的标签对象
        return ResponseEntity.ok(Collections.singletonMap("tag", newTag));
    }
}
